package com.nidu.demo.tenant.ability;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.tenant.gateway.TenantPackageGateway;
import com.nidu.demo.tenant.model.TenantPackage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class TenantPackageDomainService {

    private final TenantPackageGateway gateway;

    /**
     * 校验租户套餐名称是否重复
     * @param name 套餐名称
     * @param excludeId 排除的ID
     */
    public void validateDuplicate(String name, Long excludeId) {
        // 检查名称是否重复
        TenantPackage tenantPackage = gateway.getByName(name);
        if (tenantPackage != null) {
            if(excludeId == null){
                throw new BizException(ErrorCodeConstants.TENANT_PACKAGE_NAME_DUPLICATE.getCode(),
                        ErrorCodeConstants.TENANT_PACKAGE_NAME_DUPLICATE.getMessage());
            } else if(!excludeId.equals(tenantPackage.getId())) {
                throw new BizException(ErrorCodeConstants.TENANT_PACKAGE_NAME_DUPLICATE.getCode(),
                        ErrorCodeConstants.TENANT_PACKAGE_NAME_DUPLICATE.getMessage());
            }
        }
    }

    /**
     * 校验租户套餐是否存在且可用
     * @param id 租户套餐ID
     */
    public TenantPackage validateTenantPackage(Long id) {
        if(id != null){
            TenantPackage tenantPackage = gateway.getById(id);
            if (tenantPackage == null) {
                throw new BizException(ErrorCodeConstants.TENANT_PACKAGE_NOT_FOUND.getCode(),
                        ErrorCodeConstants.TENANT_PACKAGE_NOT_FOUND.getMessage());
            }
            tenantPackage.isDisable();
            tenantPackage.isDeleted();
            return tenantPackage;
        }
        return null;
    }
}
